package com.maoslv.controller;

import com.maoslv.aop.LogAnnotation;
import com.maoslv.dto.Result;
import com.maoslv.pojo.Info;
import com.maoslv.pojo.User;
import com.maoslv.service.personal.PersonalService;
import com.maoslv.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.ParseException;
import java.util.Map;

@RestController
@RequestMapping("/personal")
public class PersonalController {
    @Autowired
    PersonalService personalService;

    @Autowired
    UserService userService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/updatePass/{id}")
    @LogAnnotation(operator = "更新密码")
    public Result getPass(@PathVariable Integer id, @RequestBody Map<String,String> pass) {
        String oldPass = pass.get("oldPass");
        String newPass = pass.get("newPass");
        String rNewPass = pass.get("rNewPass");
        if (!newPass.equals(rNewPass)) {
            return Result.fail("两次新密码不一致");
        }
        String password = personalService.getPass(id);
        if (bCryptPasswordEncoder.matches(oldPass,password)) {
            personalService.updatePass(id,bCryptPasswordEncoder.encode(newPass));
            return Result.succ("修改成功",null);
        } else {
            return Result.fail("旧密码错误");
        }
    }

    @GetMapping("/info")
    @LogAnnotation(operator = "获取个人信息")
    public Result getInfo(Principal principal) {
        User user = userService.getByUsername(principal.getName());
        User info = personalService.getInfo(user.getInfoId(),user.getId());
        return Result.succ("获取成功",info);
    }

    @PostMapping("/updateInfo")
    @LogAnnotation(operator = "更新个人信息")
    public Result updateInfo(@RequestBody Info info) throws ParseException {
        if (personalService.updateInfo(info) > 0) {
            return Result.succ("编辑成功",null);
        }
        return Result.fail("编辑失败");
    }

    @GetMapping("/getFormInfo/{id}")
    @LogAnnotation(operator = "获取编辑表单个人信息")
    public Result getFormInfo(@PathVariable Integer id) {
        Info fromInfo = personalService.getFormInfo(id);
        return Result.succ("获取成功",fromInfo);
    }
}
